package libs

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

const (
	USER     = "root"
	PASSWORD = "1q2w3e4r"
	DRIVER   = "mysql"
	SCHEMA   = "tcp"
	HOST     = "127.0.0.1"
	PORT     = 3306
	DBNAME   = "test"
	CHARSET  = "utf8"
)

// func QueryDb2() {
// 	connectInfo := fmt.Sprintf("%s:%s@%s(%s:%d)/%s?charset=%s", USER, PASSWORD, SCHEMA, HOST, PORT, DBNAME, CHARSET)
// 	db, err := sql.Open(DRIVER, connectInfo)
// 	if err != nil {
// 		panic("数据库连接失败!")
// 	}
// 	defer db.Close()
// 	rows, err := db.Query("select * from go_user")
// 	if err != nil {
// 		panic("查询错误!")
// 	}
// 	defer rows.Close()
// 	type fields struct {
// 		id   int
// 		name string
// 	}
// 	var result fields
// 	// Columns, err := rows.Columns()
// 	r := make([]fields, 0)
// 	for rows.Next() {
// 		if err != nil {
// 			panic("数据库错误")
// 		}
// 		fmt.Println()
// 		rows.Scan(&result.id, &result.name)
// 		r = append(r, result)
// 	}

// 	for _, v := range r {
// 		fmt.Printf("id是:%d,name是:%s", v.id, v.name)
// 		fmt.Println()
// 	}
// 	// fmt.Printf("%+v", r)
// }
func connect() (*sql.DB, interface{}) {
	connectInfo := fmt.Sprintf("%s:%s@%s(%s:%d)/%s?charset=%s", USER, PASSWORD, SCHEMA, HOST, PORT, DBNAME, CHARSET)
	return sql.Open(DRIVER, connectInfo)
}

//查询语句
func QueryDb(querySql string, args ...interface{}) []map[string]string {
	db, err := connect()
	if err != nil {
		panic(err)
	}
	defer db.Close()
	rows, err := db.Query(querySql, args...)
	if err != nil {
		panic("查询错误!")
	}
	defer rows.Close()
	//获取列名
	columns, _ := rows.Columns()
	// fmt.Printf("%#v", columns)
	//定义一个切片,长度是字段的个数,切片里面的元素类型是sql.RawBytes
	values := make([]sql.RawBytes, len(columns))
	//定义一个切片,元素类型是interface{} 接口
	scanArgs := make([]interface{}, len(values))
	for i := range values {
		//把sql.RawBytes类型的地址存进去了
		scanArgs[i] = &values[i]
	}

	//获取字段值
	var result []map[string]string
	for rows.Next() {
		res := make(map[string]string)
		rows.Scan(scanArgs...)
		for i, col := range values {
			res[columns[i]] = string(col)
		}
		result = append(result, res)
	}
	//遍历结果
	return result
}
func QueryRowDb(ExcSql string, args ...interface{}) map[string]string {
	db, err := connect()

	if err != nil {
		panic(err)
	}
	defer db.Close()
	// rows := db.QueryRow(ExcSql, args...)
	return QueryDb(ExcSql, args...)[0]
}
func ExcuteDb(execSql string, args ...interface{}) (int64, int64) {
	db, err := connect()
	if err != nil {
		panic(err)
	}
	defer db.Close()
	result, err := db.Exec(execSql, args...)
	if err != nil {
		panic(err)
	}
	RowsAffected, _ := result.RowsAffected()
	LastInsertId, _ := result.LastInsertId()
	return RowsAffected, LastInsertId
}
